from django.core.management import setup_environ
import sys
import os
import time
from datetime import datetime, timedelta

sys.path.append(os.path.abspath("../"))
import settings
setup_environ(settings)
import stream.feeds as feeds
from stream import models
sys.path.pop()

from django.db.models import Q
from django.db import transaction

UPDATE_PERIOD = timedelta(minutes = 30)

def updateStaleChannels(period, force_update = False):
    """
    Update all feeds which hahave not been updated for more than period.
    """
    transaction.enter_transaction_management(managed=False)
    transaction.managed(False)
    stale_channels = []
    for cls in [models.FeedChannel, models.DeliciousChannel, models.TwitterChannel]:
        try:
            if not force_update:
                new_stale_channels = cls.objects.filter(Q(last_updated__lt = datetime.utcnow() - cls.UPDATE_PERIOD) | Q(last_updated__isnull = True))
            else:
                new_stale_channels = cls.objects.all()
            update_limit = getattr(cls, 'UPDATE_LIMIT', None)
            if update_limit is not None:
                # Have to simulate negative index
                length = new_stale_channels.count()
                if length > update_limit:
                    new_stale_channels = new_stale_channels[length - update_limit:length]
            stale_channels.extend(new_stale_channels)
        except Exception, e:
            print e
    for channel in stale_channels:
        try:
            channel.update()
            transaction.commit()
        except Exception, e:
            transaction.rollback()
            print e
    transaction.leave_transaction_management()

if __name__ == "__main__":
    force_update = False
    for argument in sys.argv[1:]:
        if argument == '--force':
            force_update = True
    updateStaleChannels(UPDATE_PERIOD, force_update)
